package com.study.talk.ui.app.moment

import android.app.Application
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.study.common.ToastUtil
import com.study.talk.R
import com.study.talk.ui.app.base.BaseViewModel
import com.study.talk.data.model.vo.MomentVo
import com.study.talk.utils.FileUtil
import com.study.talk.utils.extras.useful
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import top.zibin.luban.Luban
import javax.inject.Inject

@HiltViewModel
class AddMomentViewModel @Inject constructor(application: Application) :
    BaseViewModel(application) {

    private val _choose =
        Uri.parse("android.resource://${app.packageName}/${R.drawable.choose_image}")

    private val _imagesUri = MutableLiveData<List<Uri>>(mutableListOf(_choose))
    val imagesUri: LiveData<List<Uri>> get() = _imagesUri

    private val _complete = MutableLiveData(false)
    val complete: LiveData<Boolean> get() = _complete

    val content = MutableLiveData("")

    fun changeImagesUri(images: MutableList<Uri>) {
        if (images.size < 9 && images.last() != _choose) images.add(_choose)
        _imagesUri.postValue(images)
    }

    fun submit() {
        imagesUri.value?.let {
            if (content.value?.useful() == false) {
                ToastUtil.showToast(app, "请输入动态内容")
                return
            }
            val pathsSource = mutableListOf<String>()
            it.filter { uri -> uri != _choose }
                .mapTo(pathsSource) { uri -> FileUtil.getPathFromUri(app, uri) }
            val compressPaths = Luban.with(app).load(pathsSource).get().map { file -> file.path }
            viewModelScope.launch {
                val result = fileRepository.uploads(compressPaths)
                if (result.isEmpty()) {
                    ToastUtil.showToast(app, "图片上传失败")
                } else {
                    ToastUtil.showToast(app, "图片上传成功")
                    val momentVo = MomentVo(
                        app.userInfo,
                        result,
                        content.value!!.trim()
                    )
                    if (momentRepository.addMoment(momentVo)) {
                        ToastUtil.showToast(app, ("发布成功"))
                        _complete.postValue(true)
                    } else {
                        ToastUtil.showToast(app, "发布失败")
                    }
                }
            }
        }
    }

    fun remove(position: Int) {
        _imagesUri.value?.let {
            val mutableList = it.toMutableList()
            mutableList.removeAt(position)
            changeImagesUri(mutableList)
        }
    }

    fun isChoose(position: Int): Boolean {
        return _imagesUri.value?.get(position) == _choose
    }
}